import React, {Component} from 'react';
import {Image} from 'react-native';
import FastImage from 'react-native-fast-image';
import PropTypes from 'prop-types';

export default class AutoSizingImage extends Component {

    constructor(props){
        super(props);
        if (typeof(props.source) === 'number'){
            const data = Image.resolveAssetSource(props.source);
            console.log(data);
            this.state = {aspectRatio: data.width / data.height };
        }
        else {
            this.state = {aspectRatio: 1};
            console.log(props.source);
        }
    }

    onLoad = e => {
        if (typeof(this.props.source) === 'object'){
            const {
                nativeEvent: {width, height},
            } = e;
            console.log('auto size image:', width, height);
            this.setState({width, aspectRatio: width / height});
        }

        if (this.props.onLoad) this.props.onLoad(e);
    };


    render() {

        return (
            <FastImage
                {...this.props}
                onLoad={this.onLoad}
                style={[{width: this.props.width, aspectRatio: this.state.aspectRatio}, this.props.style]}
            >{this.props.children}</FastImage>
        );
    }
}

AutoSizingImage.propTypes = {
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    defaultHeight: PropTypes.number
};

AutoSizingImage.defaultProps = {
    defaultHeight: 10,
};
